package com.ruoyi.wjq.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.fk.domain.Question;
import com.ruoyi.fk.service.IQuestionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.wjq.domain.AnswerRecord;
import com.ruoyi.wjq.service.IAnswerRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 答题记录Controller
 * 
 * @author wjq
 * @date 2025-08-13
 */
@RestController
@RequestMapping("/wjq/answerrecord")
public class AnswerRecordController extends BaseController
{
    @Autowired
    private IAnswerRecordService answerRecordService;

    @Autowired
    private IQuestionService questionService;

    /**
     * 查询答题记录列表
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(AnswerRecord answerRecord)
    {
        startPage();
        List<AnswerRecord> list = answerRecordService.selectAnswerRecordList(answerRecord);
        return getDataTable(list);
    }
    
    /**
     * 查询答题记录与题库关联列表
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:list')")
    @GetMapping("/listWithBank")
    public TableDataInfo listWithBank(AnswerRecord answerRecord)
    {
        startPage();
        List<AnswerRecord> list = answerRecordService.selectAnswerRecordWithBankList(answerRecord);
        return getDataTable(list);
    }

    /**
     * 按题库ID查询答题记录列表
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:list')")
    @GetMapping("/listByBank/{bankId}")
    public TableDataInfo listByBank(@PathVariable("bankId") Long bankId)
    {
        startPage();
        AnswerRecord answerRecord = new AnswerRecord();
        answerRecord.setBankId(bankId);
        List<AnswerRecord> list = answerRecordService.selectAnswerRecordList(answerRecord);
        return getDataTable(list);
    }

    /**
     * 按用户ID和题库ID查询答题记录
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:list')")
    @GetMapping("/listByUserAndBank")
    public TableDataInfo listByUserAndBank(@RequestParam("userId") Long userId, @RequestParam("bankId") Long bankId)
    {
        startPage();
        AnswerRecord answerRecord = new AnswerRecord();
        answerRecord.setUserId(userId);
        answerRecord.setBankId(bankId);
        List<AnswerRecord> list = answerRecordService.selectAnswerRecordList(answerRecord);
        return getDataTable(list);
    }

    /**
     * 导出答题记录列表
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:export')")
    @Log(title = "答题记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AnswerRecord answerRecord)
    {
        List<AnswerRecord> list = answerRecordService.selectAnswerRecordList(answerRecord);
        ExcelUtil<AnswerRecord> util = new ExcelUtil<AnswerRecord>(AnswerRecord.class);
        util.exportExcel(response, list, "答题记录数据");
    }

    /**
     * 获取答题记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(answerRecordService.selectAnswerRecordById(id));
    }

    /**
     * 新增答题记录
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:add')")
    @Log(title = "答题记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AnswerRecord answerRecord)
    {
        return toAjax(answerRecordService.insertAnswerRecord(answerRecord));
    }

    /**
     * 修改答题记录
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:edit')")
    @Log(title = "答题记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AnswerRecord answerRecord)
    {
        return toAjax(answerRecordService.updateAnswerRecord(answerRecord));
    }

    /**
     * 删除答题记录
     */
    @PreAuthorize("@ss.hasPermi('wjq:answerrecord:remove')")
    @Log(title = "答题记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(answerRecordService.deleteAnswerRecordByIds(ids));
    }


    @GetMapping("/withQuestions/batch")
    public AjaxResult getBatchQuestions(@RequestParam("ids") String ids) {
        try {
            // 将逗号分隔的ID字符串转换为Long类型的列表
            if (ids.startsWith("[") && ids.endsWith("]")) {
                // 去除首尾的[]
                ids = ids.substring(1, ids.length() - 1).trim();
            }
            List<Integer> questionIds = Arrays.stream(ids.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            // 调用服务层方法查询批量题目
            List<Question> questions = new ArrayList<>();

          for (Integer questionId : questionIds) {
              Question answerRecord = questionService.selectQuestionById(questionId);
              questions.add(answerRecord);
          }

            for (Question question : questions) {
                System.out.println(question);
            }

            return AjaxResult.success(questions);
        } catch (NumberFormatException e) {
            return AjaxResult.error("ID格式不正确，请提供有效的数字ID");
        } catch (Exception e) {
            return AjaxResult.error("查询题目失败：" + e.getMessage());
        }
    }
}
